//
// Created by lymk on 2022/3/13.
//

#include "SphereMesh.h"
using namespace std;
void SphereMesh::GetVertex(std::vector<VertexIn> &InVertex,std::vector<std::vector<int>>& idx) {
    VertexIn tmp;
    for(int i=0;i<point.size();i++){
        tmp.pos = glm::vec4 (point[i],1.f);
        tmp.color = color;
        tmp.normal = tmp.pos - glm::vec4(center,0.f);
        tmp.texCoord = {0.f,0.f};
        InVertex.push_back(tmp);
    }
}

SphereMesh::SphereMesh(glm::vec3 c, float r) {
    center = c;
    radius = r;
    color = {0.f,0.f,1.f,1.f};
    Init(4,6);
}

void SphereMesh::Init(int ver,int hor) {
    const float PI = 3.1415926535898;
    auto rotateVec2 = [&](glm::vec2 mCoord,float degree)->glm::vec2{
        float radian = degree * PI/180.f;
        glm::mat2 tMat = glm::mat2(cos(degree),-sin(degree),sin(degree),cos(degree));
        return tMat * mCoord;
    };
    int preStart = -1;
    for(int i=0;i<=ver;i++) {
        if (i == 0) {
            point.emplace_back(0, 0, -radius);
            continue;
        }
        if (i == ver) {
            point.emplace_back(0, 0, radius);
            continue;
        }
        int nowStart = point.size();
        for (int j = 0; j < hor; j++) {
            float z = -radius + ((radius * 2.f) / ver) * i;
            float degree = j * 360.f / hor;
            point.emplace_back(rotateVec2({radius, 0}, degree), z);
        }
        if(preStart != -1){
            for(int j=0;j<hor;j++){
                vector<int> tmp = {nowStart+j, preStart+(j+1)%hor, nowStart+(j+1)%hor};
                index.emplace_back(tmp);
                tmp = {nowStart+j, preStart+j, preStart+(j+1)%hor};
                index.push_back(tmp);
            }
        }
        preStart = 1 + 8*(i-1);
    }
}
